<template>
    <div >
      <div class="flex-container">
      <div>
        <div>
        <el-tag>今日推荐</el-tag>
        <el-button style="margin-left: 20px;" icon="el-icon-zoom-in" size="small" type="primary" @click="changeRecommend">换一批</el-button>
      </div>
      <div  class="recommend_container">
        <div v-if="recomLoading">
          <div ref="chartContainer" style="width: 600px; height: 555px;"></div>
        </div>
        <div v-else="!recomLoading">
          <el-row :span="8">
        <el-col :span="24" v-for="(item, index) in items" :key="index" >
        <el-card :body-style="{ padding: '0px' }">
          <div class="card-container">
          <img :src="item.faviconUrl" class="image">
          <div class="text-container">
            <el-link :href="item.url" type="primary" target="_blank">{{item.title}}</el-link>
          </div>
          <el-button v-if="isVedio(item)" type="primary" icon="el-icon-s-opportunity" circle style="position: absolute;right:10px" @click="handleUrl(item)"></el-button>
        </div>
        </el-card>
        </el-col>
      </el-row>
    </div>

    </div>
      </div>
      <div>
        <div>
        <el-tag>用户信息</el-tag>
        </div>
        <el-card  style="width: 700px; margin-top: 20px; margin-left: 10px;display: flex" shadow="hover">
        <el-form :model="form" label-width="80px" size="small">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/api/user/uploadUserAvatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :data="{userAccount:this.name}">
            <img v-if="form.avatarUrl" :src="form.avatarUrl
            " class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
          <el-form-item label="用户名" style="margin-left: 150px; margin-top: -150px">
            <el-input v-model="form.username" disabled autocomplete="off" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" style="margin-left: 150px">
            <el-input v-model="form.email" autocomplete="off" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="密码" style="margin-left: 150px">
            <el-input v-model="form.password" autocomplete="off" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="创建时间" style="margin-left: 150px">
            <el-input v-model="form.createTime" disabled autocomplete="off" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="更新时间" style="margin-left: 150px">
            <el-input v-model="form.updateTime" disabled autocomplete="off" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item >
            <el-button type="primary" @click="save">保 存</el-button>
            <el-button type="primary" @click="return1">返回主页</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    </div>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="80%"
      >

      <div v-if="aiCompleted" id="jsmind_container" style="width:1200px;height: 400px;"></div>

      <div v-if="!aiCompleted">
        <el-empty description="首次生成中,请耐心等待~"></el-empty>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeDialog()">关 闭</el-button>
      </span>
    </el-dialog>
    </div>
  </template>
   
  <script>
  import { mapGetters } from 'vuex'
  import {getUserInfo,update} from '@/api/user'
  import { recommendUrls,analyseJsMind,getRecommendByUrl} from '@/api/ai'
  import * as echarts from 'echarts'
  //jsmind绘制流程图
  import 'jsmind/style/jsmind.css'
  import jsMind from 'jsmind/js-legacy/jsmind.js'
  import { setTimeout } from 'core-js'

  export default {
    name: "Info",
    computed: {
    ...mapGetters([
      'name',
      'avatar'
    ])
  },
    data() {
      return {
        dialogVisible:false,
        aiCompleted:false,
        jm:null,//思维导图的实例
        mind:{
    /* 元数据，定义思维导图的名称、作者、版本等信息 */
          "meta":{
              "name":"example",
              "author": 'jsmind',
          },
    /* 数据格式声明 */
    "format":"node_array",
    /* 数据内容 */
    "data":[
        {"id":"root", "isroot":true, "topic":"jsMind"},
        {"id":"easy", "parentid":"root", "topic":"Easy", "direction":"left"},
        {"id":"easy1", "parentid":"easy", "topic":"Easy to show"},
        {"id":"easy2", "parentid":"easy", "topic":"Easy to edit"},
        {"id":"easy3", "parentid":"easy", "topic":"Easy to store"},
        {"id":"easy4", "parentid":"easy", "topic":"Easy to embed"},
        {"id":"open", "parentid":"root", "topic":"Open Source", "expanded":false, "direction":"right"},
        {"id":"open1", "parentid":"open", "topic":"on GitHub"},
        {"id":"open2", "parentid":"open", "topic":"BSD License"},
        {"id":"powerful", "parentid":"root", "topic":"Powerful", "direction":"right"},
        {"id":"powerful1", "parentid":"powerful", "topic":"Base on Javascript"},
        {"id":"powerful2", "parentid":"powerful", "topic":"Base on HTML5"},
        {"id":"powerful3", "parentid":"powerful", "topic":"Depends on you"},
    ]
        },
        jmoptions:{                   // options 将在下一章中详细介绍
        container:'jsmind_container', // [必选] 容器的ID，或者为容器的对象
        editable:true,                // [可选] 是否启用编辑
        theme:'greensea'                // [可选] 主题
        },//思维导图的设置
        
        chartInstance:null,
        recomLoading:true,
        form: {
            avatarUrl:'',
            username:'',
            email:'',
            password:'',
            createTime:'',
            updateTime:'',
        },
        items:[],
        file:null,
      }
    },
    mounted() {
      this.initChart()
    recommendUrls({data:{userAccount:this.name}}).then(response=>{
        this.items=response.data
        this.recomLoading=false
      })
  },
    created() {
      this.GetUserInfo()
      
    },
    methods: {
      //获取用户信息
      GetUserInfo() {
        getUserInfo({data:{userAccount:this.name}}).then(response=>{
            this.form.username=this.name
            this.form.email=response.data.email
            this.form.createTime=response.data.createTime
            this.form.updateTime=response.data.updateTime
            this.form.password=response.data.password
            this.form.avatarUrl=response.data.userAvatar
        })
      },
      //保存用户信息
      save() {
        update({data:{userAccount:this.name,email:this.form.email,password:this.form.password}}).then(response=>{
            if(response.code==200){
                this.$notify({
                title: '成功',
                message: '信息更新成功！',
                type: 'success',
                duration: 5000,
            });
            this.$router.go(0)
            }

        })
      },

      // 头像上传
      handleAvatarSuccess() {
        this.$notify({
                title: '成功',
                message: '头像成功！',
                type: 'success',
                duration: 5000,
          });
      },
      //返回主页
      return1() {
        this.$router.push("/")
      },
      //echarts初始化
      initChart(){
        this.chartInstance=echarts.init(this.$refs.chartContainer);
        const option = {
        graphic: {
          elements: [
            {
              type: 'group',
              left: 'center',
              top: 'center',
              children: new Array(7).fill(0).map((val, i) => ({
                type: 'rect',
                x: i * 20,
                shape: {
                  x: 0,
                  y: -40,
                  width: 10,
                  height: 80
                },
                style: {
                  fill: '#5470c6'
                },
                keyframeAnimation: {
                  duration: 1000,
                  delay: i * 200,
                  loop: true,
                  keyframes: [
                    {
                      percent: 0.5,
                      scaleY: 0.3,
                      easing: 'cubicIn'
                    },
                    {
                      percent: 1,
                      scaleY: 1,
                      easing: 'cubicOut'
                    }
                  ]
                }
              }))
            },
            {
        type: 'text',
        left: 'center',
        top: '150', // 将文本放置在 group 下方
        style: {
          text: '内容推荐中~',
          fill: 'teal',
          font: 'bold 20px Arial',
          textAlign: 'center',
          textVerticalAlign: 'middle'
        }
      }
          ]
        }
        };
        this.chartInstance.setOption(option)
      },
      //换一批
      async changeRecommend(){
        this.recomLoading=true
        await this.$nextTick(); // 确保DOM已更新
        this.initChart()
        recommendUrls({data:{userAccount:this.name}}).then(response=>{
        this.items=response.data
        this.recomLoading=false
      })
      },
      //分析网页
      async handleUrl(data){
        var tempUrl=null
        getRecommendByUrl({data:{url:data.url}}).then(response=>{
          this.dialogVisible=true
          tempUrl=response.data
        })
        setTimeout(()=>{
          console.log(tempUrl)
          if(tempUrl.urldata==null){
          analyseJsMind({data:{url:data.url}}).then(response=>{
          if(response.code==200){
        this.aiCompleted=true
        var cleanedData=response.data
        cleanedData = cleanedData.replace(/\/\/.*$/gm, '');
        cleanedData = cleanedData.replace(/^\s*\n*\"|\"\n*\s*$/g, '');
        cleanedData = cleanedData.replace(/\s+/g, ' ');
        cleanedData = cleanedData.replace(/javascript/g,'');
        cleanedData = cleanedData.replace(/\`{3}/g, '');
        cleanedData = cleanedData.replace(/;.*$/, ';')
        this.mind=JSON.parse(cleanedData)
        console.log(this.mind)
        setTimeout(()=>{
        this.initjsMind()
        },500)
          }else{
            this.$message({
          message: '警告哦，网页内容为空！',
          type: 'warning'
        });
          }
        })
        }else{
        this.aiCompleted=true
        var cleanedData=tempUrl.urldata
        cleanedData = cleanedData.replace(/\/\/.*$/gm, '');
        cleanedData = cleanedData.replace(/^\s*\n*\"|\"\n*\s*$/g, '');
        cleanedData = cleanedData.replace(/\s+/g, ' ');
        cleanedData = cleanedData.replace(/javascript/g,'');
        cleanedData = cleanedData.replace(/\`{3}/g, '');
        cleanedData = cleanedData.replace(/;.*$/, ';')
        this.mind=JSON.parse(cleanedData)
        console.log(this.mind)
        
        setTimeout(()=>{
        this.initjsMind()
        },500)
        }
        },1000)

      },
      //初始化思维导图
      initjsMind() {

        console.log(JSON.stringify(this.mind))

        this.jm = new jsMind(this.jmoptions);
        this.jm.show(this.mind);
      },
      //关闭页面的同时，清除思维导图的实例
       closeDialog(){
        if(this.jm){
          delete this.jm;
        }
        const container = document.getElementById('jsmind_container');
        while (container.firstChild) {
            container.removeChild(container.firstChild);
        }
        this.dialogVisible=false
        this.aiCompleted=false
      },
      //判断是不是视频，由于爬虫问题
      isVedio(data){
        return !data.url.includes("bilibili")
      }
    }
  }
  </script>
   
  <style scoped>
  .flex-container {
  display: flex; /* 使容器成为 Flex 容器 */
  flex-direction: row; /* 设置子元素的排列方式为行 */
}
.card-container {
  display: flex;
  align-items: center;
}

.image {
  width: 60px;
  height: 60px;
}

.text-container {
  margin-left: 10px;
}

  .avatar-uploader {
    text-align: left;
    padding-bottom: 10px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 138px;
    height: 138px;
    line-height: 138px;
    text-align: center;
  }
  .avatar {
    width: 160px;
    height: 160px;
    display: block;
  }
  .recommend_container{
  width:700px;
  margin-top: 20px;
  border: 1px  #ccc; /* 添加边框，颜色和宽度可以根据需要调整 */
  border-radius: 3px; /* 可选，为边框添加圆角 */
  }
  </style>